%------------------------------------------------------------
% Author: vjache
% Created: 08.11.2009
% Description: TODO: Add description to iter_fchars
%------------------------------------------------------------
-module(iter_fchars).

%------------------------------------------------------------
% Include files
%------------------------------------------------------------
-include("../include/iter.hrl").
%------------------------------------------------------------
% Exported Functions
%------------------------------------------------------------
-export([new/2,
		 test/1,test1/1]).

%------------------------------------------------------------
% API Functions
%------------------------------------------------------------
new(Filepath,Encoding) when is_list(Filepath) andalso is_atom(Encoding) ->
	iter_concat:new(
	  iter:simple_immutable(
		fun()->
				case file:open(Filepath, [{encoding, Encoding}]) of
					{ok, IoDevice} ->
%% 						io:setopts(IoDevice, [{encoding, Encoding}]),
						IoDevice;
					Err={error, _Reason} ->
						throw(Err)
				end
		end, 
		fun(IoDevice) ->
				%%{ok, Data} | eof | {error, Reason}
%% 				io:setopts(IoDevice, [{encoding, Encoding}]),
				case io:get_chars(IoDevice,no_prompt, 1000000) of
					eof ->
						?EOF;
					Err={error,_Reason} ->
						throw(Err);
					Data ->
						iter:from_list(Data)
				end
		end, 
		fun(IoDevice) ->
				file:close(IoDevice)
		end)).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test(Filepath) ->
	I=iter_counter:new_progress_observer(
		new(Filepath, utf8),50000,
		fun(Note,Cnt)->
				io:format("!!!!!!! ~p[~p] ~p~n",[Note,now(),Cnt])
		end),
	iter:foreach(I,fun(_E)->
						   ok%io:format("~p",[[E]])
				 end),
	io:format("~n",[]),
	ok.
test1(Filepath) ->
	{ok,IoDev}=file:open(Filepath, [read_ahead,{encoding, utf8}]),
	read(IoDev).

read(IoDev)->
	case io:get_chars(IoDev,no_prompt, 1000000) of
		eof ->
			?EOF;
		Err={error,_Reason} ->
			throw(Err);
		_ ->
			read(IoDev)
	end.